<?php


namespace Frieza\Modules\Article\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\ArticleCounter;
use Doraemon\model\Article;
use Doraemon\model\Es\Article as eArticle;
use Doraemon\model\Member;
use Doraemon\service\Article\TodayArticle;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class ArticleListController extends Controller
{

    const ALL_ARTICLE = 0;
    const TODAY_ARTICLE = 1;
    const NOT_TODAY_ARTICLE = 2;

    const ARTICLE_MAP = [
        self::ALL_ARTICLE => '全部',
        self::TODAY_ARTICLE => '今日整屋',
        self::NOT_TODAY_ARTICLE => '非今日整屋'
    ];

    const QUALITY_PENDING = 0;
    const QUALITY_LOW = 5;
    const QUALITY_ORDINARY = 60;
    const QUALITY_HIGH = 70;
    const QUALITY_FEATURED = 80;

    const QUALITY_MAP = [
        self::QUALITY_PENDING => '未打分',
        self::QUALITY_LOW => '差',
        self::QUALITY_ORDINARY => '普通',
        self::QUALITY_HIGH => '优秀',
        self::QUALITY_FEATURED => '精选'
    ];

    const NOT_CLASSIFY = '0';

    public function index(Request $request, Content $content)
    {
        Admin::script($this->adminCopy());
        $result = $this->buildParams($request);
        $articleInfos = [];
        $total = $result['total'] ?? 0;
        $options = [
            'keyName' => 'aid',
            'perPage' => $request->input('per_page') ?: 20
        ];
        if (!empty($result['rows'])) {
            $articleIds = array_column($result['rows'], 'id');
            $articleInfos = Article::select("*", [
                "AND" => [
                    "aid" => $articleIds,
                    "status[!]" => [
                        Article::STATUS_DELETE
                    ]
                ],
                'ORDER' => ['publish_time' => 'DESC']
            ]);
            $articleInfos = array_column($articleInfos, null, 'aid');
            $uids = array_column($articleInfos, 'uid');
            $userInfos = Member::getUserInfoByIds($uids);
            $nickNames = array_column($userInfos, 'nick', 'uid');
            //今日整屋
            $todayArticleInfo = TodayArticle::getTodayArticlesByIds($articleIds);
            $count = ArticleCounter::getMulti($articleIds);
            //数据处理
            foreach ($articleInfos as $articleId => $articleInfo) {
                $articleInfos[$articleId]['today_article_addtime'] = $todayArticleInfo[$articleId];
                $articleInfos[$articleId]['nick'] = $nickNames[$articleInfo['uid']];
                $articleInfos[$articleId]['like'] = $count[$articleId]['like'];
                $articleInfos[$articleId]['favorite'] = $count[$articleId]['favorite'];
                $articleInfos[$articleId]['comment'] = $count[$articleId]['comments'];
            }
        }
        $gridModel = new pGridDataModel($articleInfos, $total, $options);
        $gridList = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();
            //过滤器
            $grid->filter(function (Grid\Filter $filter) {
                $this->getFilter($filter);
            });
            $grid->column('aid', 'id')->width(150)->link(function () {
                return 'https://m.haohaozhu.cn/bangyang/' . $this->aid . '.html?preview=1';
            });
            $grid->column('uid', '用户信息')->display(function () {
                return '<strong>[uid]:</strong>' . $this->uid . "<br>" .
                    '<strong>[昵称]:</strong>' . "<br>" . $this->nick . "<br><br>" .
                    "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->aid' >复制链接</a>";
            })->width(150);
            $grid->column('title', '文章信息')->display(function () {
                if ($this->today_article_addtime) {
                    $addtimeString = '<br><i class="fa fa-star" style="color: #FFD700"></i><strong>[今日整屋添加时间:]:</strong>' . "<br>" . date("Y-m-d H:i:s", $this->today_article_addtime);
                }
                return '<strong>[标题]:</strong>' . $this->title . "<br>" .
                    '<strong>[标签]:</strong>' . $this->admin_tag . "<br>" .
                    '<strong>[描述]:</strong>' . "<br>" . $this->remark . "<br>" .
                    $addtimeString;

            });
            $grid->column('like', '点赞数')->sortable()->width(80);
            $grid->column('favorite', '收藏数')->sortable()->width(80);
            $grid->column('comment', '评论数')->sortable()->width(80);
            $grid->column('publish_time', '时间')->display(function () {
                return date('Y-m-d H:i:s', $this->addtime);
            })->width(150)->sortable();
            $grid->column('admin_score', '分数')->display(function () {
                switch ($this->admin_score) {
                    case self::QUALITY_LOW :
                        return "<h3><span class='label label-danger'>" . self::QUALITY_MAP[self::QUALITY_LOW] . "</span></h3><br>";
                    case self::QUALITY_ORDINARY :
                        return "<h3><span class='label label-warning'>" . self::QUALITY_MAP[self::QUALITY_ORDINARY] . "</span></h3><br>";
                    case self::QUALITY_HIGH :
                        return "<h3><span class='label label-info'>" . self::QUALITY_MAP[self::QUALITY_HIGH] . "</span></h3><br>";
                    case self::QUALITY_FEATURED :
                        return "<h3><span class='label label-success'>" . self::QUALITY_MAP[self::QUALITY_FEATURED] . "</span></h3><br>";
                    case self::QUALITY_PENDING :
                    default :
                        return "<h3><span class='label label-default'>" . self::QUALITY_MAP[self::QUALITY_PENDING] . "</span></h3><br>";
                }
            });
        });
        return $content->body($gridList)
            ->header('整屋列表页');
    }

    private function getFilter(Grid\Filter $filter)
    {
        $filter->disableIdFilter();
        $filter->column(4, function (Grid\Filter $filter) {
            $filter->dropDown('search_type', [
                    'uid' => 'uid',
                    'article_id' => 'article_id'
                ]
            );
            $filter->dropDown('search_keyword', [
                'title' => '标题',
                'remark' => '描述']);
        });

        $filter->column(6, function (Grid\Filter $filter) {
            $filter->equal('score', '质量')->checkbox(self::QUALITY_MAP);
            $filter->between('time', '发布时间')->date();
            $filter->expand();
        });

    }

    private function buildParams(Request $request)
    {
        $search = $request->input();
        $where = [];
        $defaultResult = [
            'rows' => [],
            'total' => 0,
        ];
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        //整屋id
        if (!empty($search['article_id'])) {
            $defaultResult['rows'][] = ['id' => $search['article_id']];
            $defaultResult['total'] = 1;
            return $defaultResult;
        }
        //uid
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $where['uid'] = $search['uid'];
        }
        //开始时间
        if (!isset($search['time']['end'], $search['time']['start'])) {
            $request->merge([
                'time' => [
                    'start' => '2015-01-01',
                    'end' => date('Y-m-d H:i:s'),
                ]
            ]);
            $search['time']['start'] = '2015-01-01';
            $search['time']['end'] = date('Y-m-d H:i:s');
        }
        if (isset($search['time']['start']) && $search['time']['start'] !== '') {
            $where['publish_time[>=]'] = strtotime($search['time']['start']);
        }
        //结束时间
        if (isset($search['time']['end']) && $search['time']['end'] !== '') {
            $where['publish_time[<=]'] = strtotime($search['time']['end']);
        }
        //标题
        if (isset($search['title']) && $search['title'] !== '') {
            $where['title'] = $search['title'];
        }
        //描述
        if (isset($search['remark']) && $search['title'] !== '') {
            $where['adm_remark'] = $search['remark'];
        }
        //打分
        if (isset($search['score'])) {
            $where['admin_score'] = $search['score'];
        }
        //limit
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        //排序
        if (isset($search['_sort'])) {
            if ($search['_sort']['type'] === 'desc') {
                $order = eArticle::DESC;
            } else {
                $order = eArticle::ASC;
            }
            $where['ORDER'] = [$search['_sort']['column'] => $order];
        } else {
            $where['ORDER'] = ['publish_time' => eArticle::DESC];
        }
        return eArticle::getInfosByParams($where, 'id');
    }

    public function copyUrl($id)
    {
        return Hhzurl::h5BangyangShow($id);
    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
SCRIPT;
    }
}